const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
require('dotenv').config();

// MongoDB连接配置
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://gof23user:gof23password@localhost:27017/gof23-game';

// 读取初始化数据
const readInitData = () => {
  try {
    const dataPath = path.join(__dirname, '../docker/mongo-init.js');
    const content = fs.readFileSync(dataPath, 'utf8');
    return content;
  } catch (err) {
    console.error('Error reading initialization data:', err);
    return null;
  }
};

// 解析mongo-init.js文件中的patterns数组
const extractPatternsFromInitScript = (script) => {
  try {
    // 使用正则表达式提取patterns数组
    const patternsMatch = script.match(/const patterns = \[([\s\S]*?)\];/);
    if (!patternsMatch) return null;
    
    // 将提取的字符串转换为可执行的JavaScript代码
    const patternsArrayString = `[${patternsMatch[1]}]`;
    // 使用eval执行代码获取数组（在这种受控的情况下使用是安全的）
    const patterns = eval(patternsArrayString);
    
    return patterns;
  } catch (err) {
    console.error('Error extracting patterns from init script:', err);
    return null;
  }
};

// 连接到MongoDB并初始化数据
const initializeData = async () => {
  try {
    console.log('Connecting to MongoDB...');
    await mongoose.connect(MONGODB_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('MongoDB connected');

    // 读取并解析初始化脚本
    const initScript = readInitData();
    if (!initScript) {
      console.error('无法读取初始化数据，请确保docker/mongo-init.js文件存在');
      return;
    }

    // 提取patterns数组
    const patterns = extractPatternsFromInitScript(initScript);
    if (!patterns || patterns.length === 0) {
      console.error('无法从初始化脚本中提取设计模式数据');
      return;
    }

    console.log(`从mongo-init.js中提取了 ${patterns.length} 个设计模式`);
    console.log('正在初始化数据...');

    // 清空集合
    console.log('清空现有集合...');
    await mongoose.connection.db.collection('patterns').deleteMany({});
    await mongoose.connection.db.collection('challenges').deleteMany({});
    
    // 创建集合（如果不存在）
    const collections = await mongoose.connection.db.listCollections().toArray();
    const collectionNames = collections.map(c => c.name);
    
    if (!collectionNames.includes('patterns')) {
      await mongoose.connection.db.createCollection('patterns');
    }

    if (!collectionNames.includes('users')) {
      await mongoose.connection.db.createCollection('users');
    }

    if (!collectionNames.includes('challenges')) {
      await mongoose.connection.db.createCollection('challenges');
    }

    if (!collectionNames.includes('progress')) {
      await mongoose.connection.db.createCollection('progress');
    }

    // 插入设计模式数据
    await mongoose.connection.db.collection('patterns').insertMany(patterns);
    console.log(`已插入 ${patterns.length} 个设计模式`);

    // 为每个设计模式创建初级挑战
    const insertedPatterns = await mongoose.connection.db.collection('patterns').find().toArray();
    const challenges = [];

    insertedPatterns.forEach(pattern => {
      // 为每个设计模式创建初级挑战
      challenges.push({
        title: `Implement a basic ${pattern.name} pattern`,
        description: `Create a simple implementation of the ${pattern.name} pattern.`,
        pattern: pattern._id,
        level: 'beginner',
        scenario: `You are tasked with a simple scenario that can be solved using the ${pattern.name} pattern.`,
        requirements: [
          `Implement the core components of the ${pattern.name} pattern.`,
          `The solution should demonstrate the main intent of the ${pattern.name} pattern.`
        ],
        hints: [
          `Review the structure of the ${pattern.name} pattern.`,
          `Focus on the roles of the main participants in the ${pattern.name} pattern.`
        ],
        sampleSolution: '// Basic implementation code here',
        testCases: [],
        timeLimit: 1800,
        difficulty: 2,
        tags: [pattern.name.toLowerCase().replace(' ', '-'), 'beginner', pattern.category.toLowerCase()]
      });
    });

    await mongoose.connection.db.collection('challenges').insertMany(challenges);
    console.log(`已插入 ${challenges.length} 个挑战`);

    // 插入测试用户（如果不存在）
    const testUserExists = await mongoose.connection.db.collection('users').findOne({ email: 'test@example.com' });
    if (!testUserExists) {
      const testUser = {
        username: 'testuser',
        email: 'test@example.com',
        password: '$2a$10$X/HsX3wnMqb3UUL9UHjbUO9RGQJnJ0JjbEiuH9.YV5xSE/2EiEMqm', // 'password'
        firstName: 'Test',
        lastName: 'User',
        role: 'user',
        createdAt: new Date(),
        progress: {
          currentLevel: 'beginner',
          currentPattern: null,
          completedPatterns: {
            beginner: [],
            intermediate: [],
            advanced: []
          }
        },
        preferences: {
          theme: 'light',
          aiProvider: 'openai',
          notifications: {
            email: true,
            push: true
          }
        }
      };

      await mongoose.connection.db.collection('users').insertOne(testUser);
      console.log('已插入测试用户: testuser (密码: password)');
    } else {
      console.log('测试用户已存在，跳过插入');
    }

    console.log('数据初始化完成!');
  } catch (err) {
    console.error('数据初始化失败:', err);
  } finally {
    await mongoose.disconnect();
    console.log('MongoDB连接已关闭');
  }
};

// 执行初始化
initializeData(); 